<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-dropdown
          @command="handleAddCommand"
          v-hasPermi="['invoice:sales_invoice:add']"
        >
          <el-button type="primary" plain icon="Plus">
            新增<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-for="item in salesInvoiceTypes"
                :key="item.id"
                :command="item.id"
              >
                {{ item.invoiceTypeName }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['invoice:sales_invoice:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['invoice:sales_invoice:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['invoice:sales_invoice:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="sales_invoiceList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="30" align="center" />
      <el-table-column label="序号" align="center" prop="salesInvoiceId" />
      <el-table-column label="发票种类" align="center" prop="invoiceTypeName" />
      <el-table-column
        label="开票日期"
        align="center"
        prop="bullingDate"
        width="180"
      />
      <el-table-column label="发票号码" align="center" prop="invoiceNumber">
        <template #default="scope">
          <el-button link type="primary" @click="handleViewInvoiceDetail(scope.row)">
            {{ scope.row.invoiceNumber }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="客户名称" align="center" prop="customerName" />
      <el-table-column
        label="业务类型"
        align="center"
        prop="businessTypeName"
      />
      <el-table-column
        label="合计金额"
        align="center"
        prop="taxExcludedAmount"
      />
      
      <el-table-column label="合计税额" align="center" prop="taxAmount" />
      <el-table-column label="价格合计" align="center" prop="totalAmount" />
      <el-table-column
        label="认证状态"
        align="center"
        prop="authenticationStatus"
      >
        <template #default="scope">
          <span v-if="scope.row.authenticationStatus == 0">已认证</span>
          <span v-else>未认证</span>
        </template>
      </el-table-column>
      <el-table-column
        label="认证日期"
        align="center"
        prop="authenticationDate"
      >
        <template #default="scope">
          <span v-if="scope.row.authenticationStatus == 0">{{ scope.row.authenticationDate }}</span>
          <span v-else>未认证</span>
        </template>
      </el-table-column>
      <el-table-column label="关联凭证" align="center" prop="voucherId">
        <template #default="scope">
          <span v-if="scope.row.voucherId != null"></span>
          <el-button v-else link type="primary" @click="handleViewVoucher()">
            生成凭证
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['invoice:sales_invoice:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['invoice:sales_invoice:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改销项发票对话框 -->
    <el-dialog :title="title" v-model="open" width="1100px" append-to-body>
      <el-form
        ref="sales_invoiceRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开票日期" prop="billingDate">
              <el-date-picker
                clearable
                v-model="form.billingDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择开票日期"
                style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col
            :span="12"
            v-if="form.invoiceTypeId == 3 || form.invoiceTypeId == 4"
          >
            <el-form-item label="全电发票号码" prop="fullElectricInvoiceNumber">
              <el-input
                v-model="form.fullElectricInvoiceNumber"
                placeholder="请输入全电发票号码"
              />
            </el-form-item>
          </el-col>
          <el-col
            :span="12"
            v-if="
              form.invoiceTypeId == 1 ||
              form.invoiceTypeId == 2 ||
              form.invoiceTypeId == 5
            "
          >
            <el-form-item label="发票代码" prop="invoiceCode">
              <el-input
                v-model="form.invoiceCode"
                placeholder="请输入发票代码"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col
            :span="12"
            v-if="
              form.invoiceTypeId == 1 ||
              form.invoiceTypeId == 2 ||
              form.invoiceTypeId == 5
            "
          >
            <el-form-item label="发票号码" prop="invoiceNumber">
              <el-input
                v-model="form.invoiceNumber"
                placeholder="请输入发票号码"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerId">
              <el-select
                v-model="form.customerId"
                placeholder="请选择客户"
                @change="handleCustomerChange"
                style="width: 100%"
              >
                <el-option
                  v-for="item in customerInfos"
                  :key="item.id"
                  :label="item.customerName"
                  :value="item.customerId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="phoneNumber">
              <el-input v-model="form.phoneNumber" placeholder="请输入电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开户行" prop="bankName">
              <el-input v-model="form.bankName" placeholder="请输入开户行" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账号" prop="accountNumber">
              <el-input v-model="form.accountNumber" placeholder="请输入账号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12" v-if="form.invoiceTypeId === 5">
            <el-form-item label="机器编号" prop="machineCode">
              <el-input v-model="form.machineCode" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.invoiceTypeId === 5">
            <el-form-item label="车架号" prop="chassisNumber">
              <el-input v-model="form.chassisNumber" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.invoiceTypeId === 5">
            <el-form-item label="主管税务机关代码" prop="taxAuthorityCode">
              <el-input v-model="form.taxAuthorityCode" placeholder="请输入" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="认证状态" prop="authenticationStatus">
              <el-radio-group v-model="form.authenticationStatus">
                <el-radio :label="0">已认证</el-radio>
                <el-radio :label="1">未认证</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否作废" prop="isCancelled">
              <el-radio-group v-model="form.isCancelled">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="认证日期"
              prop="authenticationDate"
              v-if="form.authenticationStatus === 0"
            >
              <el-date-picker
                clearable
                v-model="form.authenticationDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择认证日期"
                style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input
                v-model="form.remarks"
                type="textarea"
                placeholder="请输入备注内容"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 凭证模板部分 -->
        <div class="sub-title">凭证模板</div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="业务类型" prop="businessTypeId">
              <el-select
                v-model="form.businessTypeId"
                placeholder="请选择业务类型"
                style="width: 100%"
              >
                <el-option
                  v-for="item in businessTypeList"
                  :key="item.businessTypeId"
                  :label="item.businessTypeName"
                  :value="item.businessTypeId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模板名称" prop="templateId">
              <el-select
                v-model="form.templateId"
                placeholder="请选择模板"
                style="width: 100%"
              >
                <el-option
                  v-for="item in invoiceTemplates"
                  :key="item.templateId"
                  :label="item.templateName"
                  :value="item.templateId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 发票数据部分 -->
        <div class="sub-title">发票数据</div>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="录入发票明细" prop="isDetailEntered">
              <el-radio-group v-model="form.isDetailEntered">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 发票明细表格 -->
        <el-table
          :data="form.details || []"
          border
          style="width: 100%; margin-top: 15px"
          v-if="form.isDetailEntered === 1"
        >
          <el-table-column
            type="index"
            label="序号"
            width="50"
            align="center"
          />

          <el-table-column label="商品名称" align="center" width="110">
            <template #default="scope">
              <el-select
                v-model="scope.row.productId"
                placeholder="请选择商品"
                @change="(val) => handleProductChange(val, scope.$index)"
                style="width: 100%"
              >
                <el-option
                  v-for="item in invoiceProducts"
                  :key="item.id"
                  :label="item.productName"
                  :value="item.id"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            label="规格型号"
            align="center"
            prop="specificationModel"
          />
          <el-table-column
            label="单位"
            align="center"
            prop="unit"
            width="120"
          />
          <el-table-column label="数量" align="center" width="180">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.quantity"
                :min="1"
                :precision="0"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column label="单价" align="center" prop="unitPrice">
            <template #default="scope">
              {{ scope.row.unitPrice }}
            </template>
          </el-table-column>
          <el-table-column label="金额" align="center" prop="amount" />
          <el-table-column label="税率" align="center" prop="taxRate">
            <template #default="scope">
              {{ (scope.row.taxRate * 100).toFixed(0) + "%" }}
            </template>
          </el-table-column>
          <el-table-column label="税额" align="center" prop="taxAmount" />
          <el-table-column label="操作" width="150" align="center">
            <template #default="scope">
              <el-button
                link
                type="primary"
                icon="Plus"
                @click="handleAddDetail"
                >添加</el-button
              >
              <el-button
                link
                type="danger"
                icon="Delete"
                @click="handleDeleteDetail(scope.$index)"
                :disabled="form.details.length <= 1"
                >移除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 合计信息 -->
        <el-row :gutter="20" style="margin-top: 20px">
          <el-col :span="8">
            <el-form-item label="不含税金额" prop="taxExcludedAmount">
              <el-input
                v-model="form.taxExcludedAmount"
                placeholder="请输入不含税金额"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合计税额" prop="taxAmount">
              <el-input v-model="form.taxAmount" placeholder="请输入合计税额" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="价税合计" prop="totalAmount">
              <el-input
                v-model="form.totalAmount"
                placeholder="请输入价税合计"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- ------------------------------------------------------------------------ -->
  </div>
  <div>
    <!-- 发票详情对话框 -->
    <el-dialog
      :title="invoiceDetailTitle"
      v-model="invoiceDetailOpen"
      width="1000px"
      append-to-body
    >
      <div class="invoice-detail-container">
        <div class="invoice-header">
          <div class="header-title">{{ invoiceDetailTitle }}</div>
          <div class="header-actions">
            <el-button size="small" type="primary" @click="handleEditInvoice">编辑</el-button>
            <el-button size="small" type="primary" @click="handleAuthenticateInvoice" v-if="currentInvoice.authenticationStatus === 1">认证</el-button>
          </div>
        </div>
        
        <el-tabs v-model="activeTab">
          <el-tab-pane label="详情" name="detail">
            <div class="detail-section">
              <div class="section-title">基本信息</div>
              <div class="info-grid">
                <div class="info-row">
                  <div class="info-item">
                    <span class="label">创建人：</span>
                    <span class="value">{{ currentInvoice.createBy }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">录入时间：</span>
                    <span class="value">{{ currentInvoice.createTime }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">更新时间：</span>
                    <span class="value">{{ currentInvoice.updateTime }}</span>
                  </div>
                </div>
                
                <div class="info-row">
                  <div class="info-item">
                    <span class="label">是否作废：</span>
                    <span class="value">{{ currentInvoice.isCancelled === 1 ? '是' : '否' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">开票方式：</span>
                    <span class="value">{{ currentInvoice.invoiceTypeName }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">模版类型：</span>
                    <span class="value">{{ currentInvoice.templateName }}</span>
                  </div>
                </div>
                
                <div class="info-row">
                  <div class="info-item">
                    <span class="label">模板名称：</span>
                    <span class="value">{{ currentInvoice.templateName }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">模板税率：</span>
                    <span class="value">{{ currentInvoice.taxRate ? (currentInvoice.taxRate * 100).toFixed(0) + '%' : '-' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">关联凭证：</span>
                    <span class="value">{{ currentInvoice.voucherId || '未生成' }}</span>
                  </div>
                </div>
                
                <div class="info-row">
                  <div class="info-item">
                    <span class="label">认证状态：</span>
                    <span class="value">{{ currentInvoice.authenticationStatus === 1 ? '已认证' : '未认证' }}</span>
                  </div>
                  <div class="info-item" v-if="currentInvoice.authenticationStatus === 1">
                    <span class="label">认证日期：</span>
                    <span class="value">{{ currentInvoice.authenticationDate }}</span>
                  </div>
                </div>
              </div>
            </div>
            
            <div class="detail-section">
              <div class="section-title">开票信息</div>
              <div class="info-grid">
                <div class="info-row">
                  <div class="info-item">
                    <span class="label">开票日期：</span>
                    <span class="value">{{ currentInvoice.billingDate }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">发票代码：</span>
                    <span class="value">{{ currentInvoice.invoiceCode || '-' }}</span>
                  </div>
                </div>
                
                <div class="info-row">
                  <div class="info-item">
                    <span class="label">发票号码：</span>
                    <span class="value">{{ currentInvoice.invoiceNumber || '-' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">全电发票号码：</span>
                    <span class="value">{{ currentInvoice.fullElectricInvoiceNumber || '-' }}</span>
                  </div>
                </div>
                
                <div class="info-row">
                  <div class="info-item">
                    <span class="label">客户名称：</span>
                    <span class="value">{{ currentInvoice.customerName }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">纳税人识别号：</span>
                    <span class="value">{{ currentInvoice.taxIdentificationNumber || '-' }}</span>
                  </div>
                </div>
                
                <div class="info-row">
                  <div class="info-item">
                    <span class="label">地址：</span>
                    <span class="value">{{ currentInvoice.address || '-' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">电话：</span>
                    <span class="value">{{ currentInvoice.phoneNumber || '-' }}</span>
                  </div>
                </div>
                
                <div class="info-row">
                  <div class="info-item">
                    <span class="label">开户行：</span>
                    <span class="value">{{ currentInvoice.bankName || '-' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">账号：</span>
                    <span class="value">{{ currentInvoice.accountNumber || '-' }}</span>
                  </div>
                </div>
              </div>
            </div>
            
            <div class="detail-section">
              <div class="section-title">凭证模板</div>
              <div class="info-grid">
                <div class="info-row">
                  <div class="info-item">
                    <span class="label">业务类型：</span>
                    <span class="value">{{ currentInvoice.businessTypeName }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">模板名称：</span>
                    <span class="value">{{ currentInvoice.templateName }}</span>
                  </div>
                </div>
              </div>
            </div>
            
            <div class="detail-section">
              <div class="section-title">发票数据</div>
              <div class="info-grid">
                <div class="info-row">
                  <div class="info-item">
                    <span class="label">录入发票明细：</span>
                    <span class="value">{{ currentInvoice.isDetailEntered === 1 ? '是' : '否' }}</span>
                  </div>
                </div>
              </div>
              
              <el-table :data="currentInvoice.invoiceProducts || []" border style="width: 100%; margin-top: 15px">
                <el-table-column type="index" label="序号" width="50" align="center" />
                <el-table-column label="商品名称" prop="productName" align="center" />
                <el-table-column label="规格型号" prop="specificationModel" align="center" />
                <el-table-column label="单位" prop="unit" align="center" width="80" />
                <el-table-column label="数量" prop="quantity" align="center" width="80" />
                <el-table-column label="单价" prop="unitPrice" align="center" width="100" />
                <el-table-column label="金额" prop="productAmound" align="center" width="100" />
                <el-table-column label="税率" align="center" width="80">
                  <template #default="scope">
                    {{ scope.row.taxRate ? (scope.row.taxRate * 100).toFixed(0) + '%' : '-' }}
                  </template>
                </el-table-column>
                <el-table-column label="税额" prop="productRate" align="center" width="100" />
                <el-table-column label="征税项目" prop="projectName" align="center" />
                <el-table-column label="计税方法" prop="methodName" align="center" />
              </el-table>
              
              <div class="invoice-summary">
                <div class="summary-item">
                  <span>不含税金额：</span>
                  <span class="amount">{{ currentInvoice.taxExcludedAmount }}</span>
                </div>
                <div class="summary-item">
                  <span>税额：</span>
                  <span class="amount">{{ currentInvoice.taxAmount }}</span>
                </div>
                <div class="summary-item">
                  <span>价税合计：</span>
                  <span class="amount">{{ currentInvoice.totalAmount }}</span>
                </div>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="变更记录" name="changes">
            <div class="changes-list">
              <!-- 这里可以添加变更记录的内容 -->
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Sales_invoice">
import {
  listSales_invoice,
  getSales_invoice,
  delSales_invoice,
  addSales_invoice,
  updateSales_invoice,
  getSelectAllData,
} from "@/api/invoice/sales_invoice";
import { get } from "@vueuse/core";
import { ref } from "vue";

const { proxy } = getCurrentInstance();
const { authentication_or_not } = proxy.useDict("authentication_or_not");

const sales_invoiceList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    invoiceTypeId: [
      { required: true, message: "发票种类id不能为空", trigger: "blur" },
    ],
    billingDate: [
      { required: true, message: "开票日期不能为空", trigger: "blur" },
    ],
    customerId: [
      { required: true, message: "客户id不能为空", trigger: "blur" },
    ],
    businessTypeId: [
      { required: true, message: "业务类型id不能为空", trigger: "blur" },
    ],
    templateId: [
      { required: true, message: "模版id不能为空", trigger: "blur" },
    ],
    taxExcludedAmount: [
      { required: true, message: "不含税金额不能为空", trigger: "blur" },
    ],
    taxAmount: [
      { required: true, message: "合计税额不能为空", trigger: "blur" },
    ],
    totalAmount: [
      { required: true, message: "合计价格不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询销项发票列表 */
function getList() {
  loading.value = true;
  listSales_invoice(queryParams.value).then((response) => {
    sales_invoiceList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    salesInvoiceId: null,
    invoiceTypeId: null,
    billingDate: null,
    invoiceCode: null,
    invoiceNumber: null,
    fullElectricInvoiceNumber: null,
    isCancelled: 0,
    customerId: null,
    address: null,
    phoneNumber: null,
    bankName: null,
    accountNumber: null,
    chassisNumber: null,
    machineCode: null,
    taxAuthorityCode: null,
    authenticationStatus: 1,
    authenticationDate: null,
    remarks: null,
    businessTypeId: null,
    templateId: null,
    isDetailEntered: 0,
    taxExcludedAmount: null,
    taxAmount: null,
    totalAmount: null,
    details: [
      {
        productId: null,
        specificationModel: "",
        unit: "",
        quantity: 1,
        unitPrice: 0,
        productAmound: 0,
        taxRate: 0,
        productRate: 0,
      },
    ],
  };
  proxy.resetForm("sales_invoiceRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.salesInvoiceId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加销项发票";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _salesInvoiceId = row.salesInvoiceId || ids.value;
  getSales_invoice(_salesInvoiceId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改销项发票";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["sales_invoiceRef"].validate((valid) => {
    if (valid) {
      if (form.value.salesInvoiceId != null) {
        updateSales_invoice(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSales_invoice(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getSelectAll();
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _salesInvoiceIds = row.salesInvoiceId || ids.value;
  proxy.$modal
    .confirm('是否确认删除销项发票编号为"' + _salesInvoiceIds + '"的数据项？')
    .then(function () {
      return delSales_invoice(_salesInvoiceIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
      getSelectAll();
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "invoice/sales_invoice/export",
    {
      ...queryParams.value,
    },
    `sales_invoice_${new Date().getTime()}.xlsx`
  );
}

const salesInvoiceTypes = ref([]); // 发票种类
const businessTypeList = ref([]); // 业务类型
const invoiceTemplates = ref([]); // 发票模板
const invoiceProducts = ref([]); // 发票商品
const customerInfos = ref([]); // 客户信息

//
function getSelectAll() {
  getSelectAllData().then((response) => {
    console.log(response.data);
    salesInvoiceTypes.value = response.data.salesInvoiceList;
    businessTypeList.value = response.data.businessTypeList;
    invoiceTemplates.value = response.data.invoiceTemplates;
    invoiceProducts.value = response.data.invoiceProducts;
    customerInfos.value = response.data.customerInfos;
  });
}

/** 处理新增下拉菜单命令 */
function handleAddCommand(command) {
  reset();
  form.value.invoiceTypeId = command;
  // 根据选择的发票类型设置标题
  const selectedType = salesInvoiceTypes.value.find(
    (item) => item.id === command
  );
  if (selectedType) {
    title.value = `添加${selectedType.invoiceTypeName}`;
  } else {
    title.value = "新增销项发票";
  }
  open.value = true;
}

// 添加发票明细行
function handleAddDetail() {
  if (!form.value.details) {
    form.value.details = [];
  }
  form.value.details.push({
    productId: null,
    specificationModel: "",
    unit: "",
    quantity: 1,
    unitPrice: 0,
    amount: 0,
    taxRate: 0,
    taxAmount: 0,
  });
}

// 删除发票明细行
function handleDeleteDetail(index) {
  form.value.details.splice(index, 1);
}

// 监听数量和单价变化，计算金额
watch(
  () => form.value.details,
  (newVal) => {
    if (newVal) {
      newVal.forEach((item) => {
        // 计算金额
        item.amount = (item.quantity * item.unitPrice).toFixed(2);
        // 计算税额
        item.productRate = (item.amount * item.taxRate).toFixed(2);
      });

      // 计算合计
      calculateTotal();
    }
  },
  { deep: true }
);

// 计算合计金额
function calculateTotal() {
  if (form.value.details && form.value.details.length > 0) {
    // 计算不含税金额
    form.value.taxExcludedAmount = form.value.details
      .reduce((sum, item) => {
        return sum + parseFloat(item.amount || 0);
      }, 0)
      .toFixed(2);

    // 计算合计税额
    form.value.taxAmount = form.value.details
      .reduce((sum, item) => {
        return sum + parseFloat(item.taxAmount || 0);
      }, 0)
      .toFixed(2);

    // 计算价税合计
    form.value.totalAmount = (
      parseFloat(form.value.taxExcludedAmount) +
      parseFloat(form.value.taxAmount)
    ).toFixed(2);

    //
  }
}

// 处理客户选择变更
function handleCustomerChange(customerId) {
  if (customerId) {
    // 查找选中的客户信息
    const selectedCustomer = customerInfos.value.find(
      (item) => item.customerId === customerId
    );
    if (selectedCustomer) {
      // 填充客户相关信息
      form.value.address = selectedCustomer.address || "";
      form.value.phoneNumber = selectedCustomer.phoneNumber || "";
      form.value.bankName = selectedCustomer.bankName || "";
      form.value.accountNumber = selectedCustomer.accountNumber || "";
    }
  } else {
    // 清空客户相关信息
    form.value.address = "";
    form.value.phoneNumber = "";
    form.value.bankName = "";
    form.value.accountNumber = "";
  }
}

// 处理商品选择变更
function handleProductChange(productId, index) {
  if (productId) {
    // 查找选中的商品信息
    const selectedProduct = invoiceProducts.value.find(
      (item) => item.id === productId
    );
    if (selectedProduct) {
      // 填充商品相关信息
      form.value.details[index].specificationModel =
        selectedProduct.specificationModel || "";
      form.value.details[index].id = selectedProduct.id || "";
      form.value.details[index].unit = selectedProduct.unit || "";
      // 确保税率是标准格式
      form.value.details[index].taxRate = parseFloat(
        selectedProduct.taxRate || 0
      ).toFixed(2);

      // 如果有单价信息，也可以填充
      if (selectedProduct.unitPrice) {
        form.value.details[index].unitPrice = selectedProduct.unitPrice;
        // 计算金额和税额
        const amount = (form.value.details[index].quantity * selectedProduct.unitPrice).toFixed(2);
        form.value.details[index].productAmound = amount;
        form.value.details[index]. productRate= (amount * form.value.details[index].taxRate).toFixed(2);
      }
      // 重新计算总计
      calculateTotal();
    }
  } else {
    // 清空商品相关信息
    form.value.details[index].specificationModel = "";
    form.value.details[index].unit = "";
    form.value.details[index].unitPrice = 0;
    form.value.details[index].taxRate = 0;
    form.value.details[index].amount = 0;
    form.value.details[index].taxAmount = 0;
    // 重新计算总计
    calculateTotal();
  }
}


// 监听数量和单价变化，计算金额
watch(
  () => form.value.details,
  (newVal) => {
    if (newVal) {
      newVal.forEach((item) => {
        // 计算金额
        const productAmound = (item.quantity * item.unitPrice).toFixed(2);
        item.productAmound = productAmound;
        // 计算税额
        item.taxAmount = (productAmound * item.taxRate).toFixed(2);
      });

      // 计算合计
      calculateTotal();
    }
  },
  { deep: true }
);


// 在现有变量声明后添加
const invoiceDetailOpen = ref(false);
const invoiceDetailTitle = ref('');
const currentInvoice = ref({});
const activeTab = ref('detail');

// 查看发票详情
function handleViewInvoiceDetail(row) {
  getSales_invoice(row.salesInvoiceId).then(response => {
    currentInvoice.value = response.data;
    invoiceDetailTitle.value = `${row.invoiceTypeName}_${row.invoiceNumber || row.fullElectricInvoiceNumber}`;
    invoiceDetailOpen.value = true;
  });
}

// 编辑发票
function handleEditInvoice() {
  invoiceDetailOpen.value = false;
  handleUpdate(currentInvoice.value);
}

// 认证发票
function handleAuthenticateInvoice() {
  proxy.$modal.confirm('确认要认证该发票吗？').then(() => {
    const params = {
      salesInvoiceId: currentInvoice.value.salesInvoiceId,
      authenticationStatus: 0,
      authenticationDate: new Date().toISOString().split('T')[0]
    };
    
    updateSales_invoice(params).then(response => {
      proxy.$modal.msgSuccess("认证成功");
      invoiceDetailOpen.value = false;
      getList();
    });
  }).catch(() => {});
}

getSelectAll();
getList();
</script>


<style scoped>
.sub-title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0 10px 0;
  padding-left: 10px;
  border-left: 3px solid #409EFF;
}

.invoice-detail-container {
  padding: 0 10px;
}

.invoice-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
}

.detail-section {
  margin-bottom: 25px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.section-title {
  background-color: #f5f7fa;
  padding: 10px 15px;
  font-weight: bold;
  border-bottom: 1px solid #ebeef5;
}

.info-grid {
  padding: 15px;
}

.info-row {
  display: flex;
  margin-bottom: 15px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-item {
  flex: 1;
  min-width: 0;
  margin-right: 20px;
}

.info-item:last-child {
  margin-right: 0;
}

.label {
  color: #606266;
  margin-right: 5px;
}

.value {
  color: #303133;
  font-weight: 500;
}

.invoice-summary {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
  padding: 10px 0;
  border-top: 1px solid #ebeef5;
}

.summary-item {
  margin-left: 30px;
}

.amount {
  font-weight: bold;
  color: #f56c6c;
}

.changes-list {
  padding: 15px;
}
</style>
